package com.stylefeng.guns.modular.system.controller;

import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.util.FileUtil;
import com.stylefeng.guns.core.util.SpringContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
@RequestMapping(value = "/file")
public class FileController {

    @RequestMapping(value = "/upload")
    @ResponseBody
    public Map<String,Object> upload(@RequestParam MultipartFile file, HttpServletRequest request)
    {
        String fileName = file.getOriginalFilename();
        fileName = FileUtil.renameToUUID(fileName);
        GunsProperties gunsProperties = SpringContextHolder.getBean(GunsProperties.class);
        fileName ="/files/" + fileName;
        Map<String,Object> resultMap = new HashMap<>();
        List<String> data = new ArrayList<>();
        data.add(fileName);
        resultMap.put("data",data);
        try {
            FileUtil.uploadFile(file.getBytes(),gunsProperties.getFileUploadPath(), fileName);
            resultMap.put("errno",0);
        } catch (Exception e) {
            resultMap.put("errno","-1");
        }
        return resultMap;
    }
}
